package com.laxcen.basiclib.core.permission;

import android.app.Activity;
import android.view.Gravity;

import com.laxcen.basiclib.base.BaseDialog;
import com.laxcen.basiclib.ui.dialog.AlertDialog;
import com.tbruyelle.rxpermissions2.RxPermissions;

public class PermissionManager {
    public static PermissionManager get(Activity activity){
        return new PermissionManager(activity);
    }
    private Activity activity;
    private RxPermissions permissions ;
    public PermissionManager(Activity activity){
        this.activity = activity;
        this.permissions = new RxPermissions(activity);
    }
    public void check(String[] permission,AfterDo afterDo){
        permissions.request(
                permission)
                .subscribe(isOk -> {
                    if (isOk){
                        afterDo.onAfter();
                    }else{
                        showAlert(permission,afterDo);
                    }
                });
    }
    private void showAlert(String[] permission,AfterDo afterDo){
        String per = "";
        for(String p:permission){
            per+="\n"+p;
        }
        AlertDialog alertDialog = new AlertDialog(activity);
        alertDialog.setTitle("您需要授权以下权限给应用:");
        alertDialog.setContent("需要以下权限:"+per);
        alertDialog.setSubmitTxt("确定");
        alertDialog.setCancelTxt("取消");
        alertDialog.setOnResult(new BaseDialog.OnResult() {
            @Override
            public void onYes() {
                check(permission,afterDo);
            }

            @Override
            public void onNo() {

            }
        });
        alertDialog.show(0, Gravity.CENTER);
    }
    public interface AfterDo{
        void onAfter();
    }
}
